import sqlite3
from hashlib import sha256

class Database:
    def __init__(self):
        self.conn = sqlite3.connect("users.db")
        self.cursor = self.conn.cursor()
        self._create_table()

    def _create_table(self):
        self.cursor.execute("""
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                username TEXT UNIQUE NOT NULL,
                password TEXT NOT NULL
            )
        """)
        self.conn.commit()

    def register_user(self, username, password):
        hashed = sha256(password.encode()).hexdigest()
        try:
            self.cursor.execute("INSERT INTO users (username, password) VALUES (?, ?)",
                              (username, hashed))
            self.conn.commit()
            return True
        except sqlite3.IntegrityError:
            return False  # 用户名已存在

    def check_login(self, username, password):
        hashed = sha256(password.encode()).hexdigest()
        self.cursor.execute("SELECT * FROM users WHERE username=? AND password=?",
                          (username, hashed))
        return self.cursor.fetchone() is not None

    def close(self):
        self.conn.close()